/*
File:		BitmapFont.cpp
Course:		SGD 1204
Author:		Sean A. James
Purpose:	Handel the Bitmap Fonts
*/

#include "BitmapFont.h"
#include "SGD Wrappers/CSGD_TextureManager.h"

CBitmapFont* CBitmapFont::GetInstance(void)
{
	// Lazy instantiation
	static CBitmapFont s_Instance;

	return &s_Instance;
}

CBitmapFont::CBitmapFont(void)
{
	m_nCharWidth = 0;
	m_nCharHeight = 0;

	m_nNumRows = 0;
	m_nNumCols = 0;

	m_nNumChars = m_nNumRows*m_nNumCols;
}
CBitmapFont::~CBitmapFont(void)
{
	m_pTM = nullptr;
}

void CBitmapFont::SetValues(int width, int height, int rows, int columns, char first, int file)
{
	m_nCharWidth = width;
	m_nCharHeight = height;
	m_nNumRows = rows;
	m_nNumCols = columns;
	m_nNumChars = m_nNumRows*m_nNumCols;

	m_pTM = CSGD_TextureManager::GetInstance();

	m_nImageID = file;
	m_cFirstChar = first;
}
RECT CBitmapFont::CellAlgorithm(int id)
{
	RECT rCell;

	rCell.left = (id%m_nNumRows)*m_nCharWidth;
	rCell.top = (id/m_nNumRows)*m_nCharHeight;

	rCell.right	= rCell.left+m_nCharWidth-1;
	rCell.bottom = rCell.top+m_nCharHeight-1;

	return rCell;
}
void CBitmapFont::Print(const char* szText, int nX, int nY, float fScale, DWORD dwColor)
{
	// Keep track of the starting x position (handle newlines)
	int nColStart = nX;

	// Iterate through the text string 1 char at a time
	int nLen = strlen(szText);

	for(int i = 0; i < nLen; i++)
	{
		// Get the char out of the string
		char ch = szText[i];

		// Adjust for whitespace:
		if(ch == '\n')
		{
			nY += m_nCharHeight * fScale;
			nX =  nColStart;
			continue;
		}

		// Calculate the tile ID
		int id = 0;

		if(ch >= 65 && ch <= 90)
			ch += 32;
		else if(ch >= 97 && ch <= 112)
			ch -= 32;

		id = ch - m_cFirstChar;

		// Get source rect on the image
		RECT rTile = CellAlgorithm(id);

		// Draw!
		m_pTM->Draw(m_nImageID, nX, nY, fScale, fScale, &rTile, m_nCharWidth/2.0f, m_nCharHeight/2.0f, 0, dwColor);

		// Move to the next position on screen
		int curn = 6;
		if(ch == 'I' || ch == 'i'
			|| ch == '!' || ch == ' ' || ch == '1' || ch == '\'')
			curn = 23;
		else if(ch == '(')
			curn = 18;

		nX += (m_nCharWidth-curn) * fScale;
	}
}